package com.lanou.dllo.baisibudejie.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.lanou.dllo.baisibudejie.adapater.RecommendAdapter;
import com.lanou.dllo.baisibudejie.R;
import com.lanou.dllo.baisibudejie.application.BaseApplication;
import com.lanou.dllo.baisibudejie.entity.ImageEntity;
import com.lanou.dllo.baisibudejie.entity.ImagesResult;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dllo on 15/10/31.
 */
public class RecommendFragment extends Fragment implements View.OnClickListener {

    private RecommendAdapter adapter;
    private RecyclerView recyclerView;
    private RequestQueue queue;
    private TextView news_backTv;
    private Boolean isLogin;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    /**
     * 在这个方法里面，获取传入的数据
     *
     * @param savedInstanceState
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    /**
     * 这个方法里面加载布局
     */
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_recommend, null);

        return view;
    }

    /**
     * 控件初始化在这写
     */
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
    }

    private void initView(View view) {
        recyclerView = (RecyclerView) view.findViewById(R.id.recommend_recyclerView);
        GridLayoutManager manager = new GridLayoutManager(getActivity(), 1);
        recyclerView.setLayoutManager(manager);
        adapter = new RecommendAdapter(getActivity());
        recyclerView.setAdapter(adapter);
        news_backTv = (TextView) view.findViewById(R.id.news_backTv);
        news_backTv.setOnClickListener(this);
    }

    /**
     * 数据初始化在这写
     *
     * @param savedInstanceState
     */
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
    }

    private void initData() {
        String per = "10";//数据条数
        queue = Volley.newRequestQueue(getActivity());
        String url = "http://api.budejie.com/api/api_open.php?market=taobao&maxid=&udid=359357052150266&a=newlist&appname=baisibudejie&c=data&os=4.3&client=android&userID=&page=1&per="+per+"&sub_flag=1&visiting=&type=10&time=week&mac=50%3AFC%3A9F%3AFC%3A75%3A7E&ver=6.0.1";
        StringRequest request = new StringRequest(url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        Gson gson = new Gson();
                        ImagesResult result = gson.fromJson(response, ImagesResult.class);
                        if (result != null) {
                            List<ImageEntity> list = result.getList();
                            if (list != null && list.size() > 0) {
                                adapter.addData(list);
                            }
                        }

                    }
                },
                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                // TODO Auto-generated method stub
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                try {
                    String jsonString = new String(response.data, "UTF-8");
                    return Response.success(jsonString,
                            HttpHeaderParser.parseCacheHeaders(response));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                } catch (Exception je) {
                    return Response.error(new ParseError(je));
                }
            }
        };
        queue.add(request);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.news_backTv:
                FragmentTransaction ft = getFragmentManager().beginTransaction();
                isLogin = BaseApplication.isLogin();
                if (isLogin) {
                    ft.replace(R.id.tabcontent_news, new MyNewsFragment());
                }else {
                    ft.replace(R.id.tabcontent_news, new NewsFragment());
                }
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
                ft.commit();
                break;
        }
    }
}
